REPLICATE Function in MS SQL Server and Its Equivalent in MySQL


The REPLICATE function returns a string by repeating a string value a specified number of times — usually used to format outputs. In MySQL, the same functionality is provided by the REPEAT function.

MSSQL

Syntax:

REPLICATE ( string_expression , integer_expression )

Example:

select REPLICATE('0',4);
--------------
0000

MSSQL Replicate function

select REPLICATE('0',5-datalength(rtrim(productid)))+CAST(productid as varchar), ProductID
from Production.Product order by ProductID
(No column name)  ProductID
00001             1
00002             2
00003             3
00004             4
00316             316
00317             317
00318             318

REPLICATE Example MSSQL

MySQL

In MySQL, the REPEAT function offers the same result.

Syntax:

REPEAT(str, count)

Example:

mysql> select repeat('#',4);
+---------------+
| repeat('#',4) |
+---------------+
| ####          |
+---------------+

MySQL REPEAT function

Assuming the same PRODUCT table exists in MySQL, this query gives the same result:

select concat(repeat('0',5-char_length(productid)),productid) from product

MySQL REPEAT function Example 2

Back to Converting Functions from MSSQL to MySQL